package com.dailyblue.java.project.bookstore.controller;

import com.alibaba.fastjson.JSONArray;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.dailyblue.java.project.bookstore.bean.Alipay;
import com.dailyblue.java.project.bookstore.bean.ShoppingCart;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
// 接收用户付款信息，调用支付宝接口，成功返回
@RestController  // 产生这个类的对象
@RequestMapping("/alipay")
public class AlipayController {
    @Value("${appId}")
    private String appId;
    @Value("${privateKey}")
    private String privateKey;
    @Value("${publicKey}")
    private String publicKey;
    @Value("${notifyUrl}")
    private String notifyUrl;
    @Value("${returnUrl}")
    private String returnUrl;
    @Value("${signType}")
    private String signType;
    @Value("${charset}")
    private String charset;
    @Value("${gatewayUrl}")
    private String gatewayUrl;

    private Alipay alipay;
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @RequestMapping("/pay")
    public String pay(Alipay alipay) throws AlipayApiException {
        alipay.setOut_trade_no(orderId());
        alipay.setSubject("order:" + orderId());
        this.alipay = alipay;
        // 产生Alipay客户端
        AlipayClient alipayClient = new DefaultAlipayClient(gatewayUrl, appId, privateKey, "json", charset, publicKey, signType);
        // 调用支付宝接口
        AlipayTradePagePayRequest alipayTradeAppPayRequest = new AlipayTradePagePayRequest();
        System.out.println("进入了这里：" + alipay);
        // 设置付款成功后应跳转的路径
        alipayTradeAppPayRequest.setNotifyUrl(notifyUrl);
        alipayTradeAppPayRequest.setReturnUrl(returnUrl);
        // 设置支付宝的各项参数
        String json = JSONArray.toJSONString(alipay);
        alipayTradeAppPayRequest.setBizContent(json);
        System.out.println("支付的参数是：" + json);
        System.out.println(JSONArray.toJSONString(alipayTradeAppPayRequest));
        // 生成最终的订单
        return alipayClient.pageExecute(alipayTradeAppPayRequest).getBody();

    }

    @RequestMapping("/success")
    public String success() {
        // 向rocketMQ中存放内容
        String str = alipay.getBody();
        str = str.substring(0, str.length() - 1);
        String[] books = str.split(",");
        List<ShoppingCart> carts = new ArrayList<>();
        for (int i = 0; i < books.length; i++) {
            String b = books[i];
            String[] a = b.split(".");
            ShoppingCart cart = new ShoppingCart();
            cart.setNumber(Integer.parseInt(a[1]));
            cart.setBookId(a[0]);
        }
        log.info("购买的图书信息：{}", carts);
        SendResult result = rocketMQTemplate.syncSend("bookstore:order", JSONArray.toJSONString(carts));
        log.info("result:{}", result);
        return "支付成功";
    }

    private String orderId() {
        String id = new Date().getTime() + "";
        return id;
    }
}

